'use client';
import Link from 'next/link'
import { usePathname } from 'next/navigation';
import clsx from 'clsx';
import { fetchTopNavList } from '@/app/lib/data';
import { useState, useRef, useEffect } from 'react';

const links = await fetchTopNavList();

export default function NavLinks() {
  const pathname = usePathname();
  const [hoverIndex, setHoverIndex] = useState<number | null>(null);
  const [lastHoverIndex, setLastHoverIndex] = useState<number | null>(null);
  const navRefs = useRef<(HTMLAnchorElement | null)[]>([]);
  const [navItemsMetrics, setNavItemsMetrics] = useState<{width: number; left: number}[]>([]);
  const [activeSubmenuIndex, setActiveSubmenuIndex] = useState<number | null>(null);
  
  // 获取当前活动的导航项索引
  const activeIndex = links.findIndex(link => link.href === pathname);
  
  // 测量每个导航项的宽度和位置
  useEffect(() => {
    const metrics = navRefs.current.map(ref => {
      if (!ref) return { width: 0, left: 0 };
      const rect = ref.getBoundingClientRect();
      const parentRect = ref.parentElement?.getBoundingClientRect() || { left: 0 };
      return {
        width: rect.width,
        left: rect.left - parentRect.left
      };
    });
    setNavItemsMetrics(metrics);
  }, []);
  
  // 更新最后hover的索引
  useEffect(() => {
    if (hoverIndex !== null) {
      setLastHoverIndex(hoverIndex);
    }
  }, [hoverIndex]);

  // 只在激活状态下显示线条，不跟随鼠标悬停
  const currentIndex = activeIndex;
  const showLine = activeIndex !== -1;

  return (
    <div className="relative flex">
      {/* 导航链接 */}
      {links.map((link:any, index) => {
        const hasChildren = link.child_category && link.child_category.length > 0;
        const isActive = activeSubmenuIndex === index;
        
        return (
          <div 
            key={link.name}
            className="relative"
          >
            <Link
              ref={el => navRefs.current[index] = el}
              href={link.href}
              className={clsx(
                "relative flex h-[48px] grow items-center justify-center gap-2 p-3 text-sm font-medium text-white md:flex-none md:justify-start md:p-2 md:px-3",
                isActive && "text-blue-400" // 高亮显示当前激活的菜单项
              )}
            >
              <p>{link.name}</p>
            </Link>
            {/* 跟随线条 */}
            <div
              className={clsx(
                'absolute bottom-0 h-0.5 bg-white transition-all duration-300',
                showLine ? 'opacity-100' : 'opacity-0'
              )}
              style={{
                left: '0',
                width: currentIndex !== null && navItemsMetrics[currentIndex] 
                  ? `${navItemsMetrics[currentIndex].width * 0.4}px` 
                  : lastHoverIndex !== null && navItemsMetrics[lastHoverIndex]
                    ? `${navItemsMetrics[lastHoverIndex].width * 0.4}px`
                    : '0',
              }}
            />
            
            {/* 二级下拉菜单 */}
            {hasChildren && isActive && (
              <div 
                className="absolute top-full left-0 z-10 w-auto min-w-[120px] bg-black/80 backdrop-blur-sm rounded-md shadow-lg py-2 mt-1 animate-fadeIn"
              >
                {link.child_category.map((child: any) => (
                  <Link
                    key={child.id}
                    href={child.href || '#'}
                    className="block px-4 py-2 text-sm text-white hover:bg-blue-500/20 hover:text-blue-400 transition-colors whitespace-nowrap"
                  >
                    {child.name}
                  </Link>
                ))}
              </div>
            )}
          </div>
        );
      })}
      
      
    </div>
  );
}